﻿using InventoryIssue.API.Write.Application.Command.Allocate;
using InventoryIssue.Domain;
using InventoryIssue.ErrorCode;
using InventoryIssue.Infrastructrue.Implement;
using MediatR;

namespace InventoryIssue.API.Write.Application.Handler.Allocate
{
    public class DelAllocateHandler : IRequestHandler<DelAllocateCommand, APIResult<int>>
    {
        private readonly DatabaseContext db;

        public DelAllocateHandler(DatabaseContext db)
        {
            this.db = db;
        }
        public async Task<APIResult<int>> Handle(DelAllocateCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();

            var res = await db.SqlSugar.Queryable<AllocateProductModel>()
                .Where(x => x.AllocateId == request.AllocateId)
                .FirstAsync();

            //if (res == null)
            //{
            //    result.Message = "未找到调拨单记录";
            //    result.Code = APIEnum.Fail;
            //    return result;
            //}

            res.IsDel = true;

            //await db.SqlSugar.Ado.BeginTranAsync();
            //try
            //{

            int mainUpdateCount = await db.SqlSugar.Updateable(res)
                .WhereColumns(x => x.AllocateId)
                .ExecuteCommandAsync();


            //    var products = await db.SqlSugar.Queryable<AllocateProductModel>()
            //        .Where(x => x.AllocateId == res.AllocateId)
            //        .ToListAsync();


            //    foreach (var item in products)
            //    {
            //        item.IsDel = true;
            //    }


            //    int productUpdateCount = await db.SqlSugar.Updateable(products)
            //        .WhereColumns(x => x.Id) 
            //        .ExecuteCommandAsync();


            //    await db.SqlSugar.Ado.CommitTranAsync();


            



            if (mainUpdateCount > 0)
            {
                result.Message = "删除成功";
                result.Code = APIEnum.Ok;
            }
            else
            {
                result.Message = "删除失败（主表或关联表无更新）";
                result.Code = APIEnum.Fail;
            }
            return result;

        }
           
    }
    
}